package com.apk.tools;

import brut.apktool.Main;
import com.xy.util.XmlUtil;
import java_util.coo_util.C_File;
import java_util.coo_util.Log.C_Log;
import java_util.coo_util.Log.C_LogTxtSave;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class C_Apk2Sign {
    public static void S_build(String _build, int index, String rootPath, File wordDir, String buildId) throws Exception {
        String wordPath = wordDir.getPath() + "/";
        String dirName = wordDir.getName();

        C_cmd.S_GotoPath(rootPath);
        C_File.S_CareteDir(rootPath + _build);

        C_Log.Log("build.开始__________");


        build_config setting = new build_config();
        if (!setting.S_LoadData(wordPath)) {
            return;
        }
        setting.S_SetInfo(wordDir, buildId, 2);

        S_unfoldApk(setting, _build, rootPath, wordPath);


        C_ProgressReport.S_SendProgress(setting, C_ProgressReport.o_fixData);
        S_fix_androidManifest(_build, rootPath, wordPath, setting);
        S_copyWeiXinClass(_build, rootPath, wordPath, setting);

        S_copyAssets(_build, rootPath, wordPath);
        S_copyIcon(_build, rootPath, wordPath);
        S_FixConfig(_build, rootPath, wordPath, setting);

        S_apk2build(_build, rootPath, setting);


        S_apk2Sign(_build, index, rootPath, wordPath, setting, dirName);


        //JOptionPane.showMessageDialog(null, setting.o_gameName + "--打包完成了", "好消息", JOptionPane.PLAIN_MESSAGE);
        C_LogTxtSave.S_SaveData();
    }

    //解压apk
    static void S_unfoldApk(build_config setting, String _build, String rootPath, String wordPath) throws Exception {
        C_ProgressReport.S_SendProgress(setting, C_ProgressReport.o_unzip);
        String appUnfoldPath = rootPath + _build + "/appUnfold";
        C_cmd.S_delete(appUnfoldPath);

        String apkPath = build_config.S_SearchFilePath(rootPath ,"app.apk");
        C_Log.Log("--------build.S_unfoldApk..开始.________");
        String[] args = new String[5];
        args[0] = "d";
        args[1] = "-f";
        args[2] = apkPath;
        args[3] = "-o";
        args[4] = appUnfoldPath;
        if (build_config.o_isDelectTempFile) {
            C_cmd.S_delete(args[4]);
        }
        C_Log.Log("--------build.S_unfoldApk..开始.解压apk________" + appUnfoldPath);
        Main.main(args);

        C_Log.Log("--------------build.S_unfoldApk..解压apk.结束.______" + appUnfoldPath);
    }

    static void S_fix_androidManifest(String _build, String rootPath, String wordPath, build_config setting) throws IOException {
        C_Log.Log("--------build.S_fix_androidManifest..开始.________");
        String fileName = rootPath + _build + "/appUnfold/AndroidManifest.xml";
        File file = new File(fileName);
        Document document = XmlUtil.getElement(file);
        Element root = document.getRootElement();
        Attribute package0 = root.attribute("package");
        setting.o_lastPackageName = package0.getValue();
        if (setting.o_packageName.length() > 2) {
            package0.setValue(setting.o_packageName);
        } else {
            setting.o_packageName = package0.getValue();
        }
        Element application = root.element("application");
        if (setting.o_gameName != null) {
            Attribute attribute = application.attribute("label");
            attribute.setValue(setting.o_gameName);
        }

        int length0 = setting.o_lastPackageName.length();
        Element provider = application.element("provider");
        Attribute authorities = provider.attribute("authorities");
        String value_1 = authorities.getValue();
        String value_2 = setting.o_packageName + value_1.subSequence(length0, value_1.length());
        authorities.setValue(value_2);

        if (true) {
            List<Element> list = application.elements();
            for (int i = 0; i < list.size(); i++) {
                Element element = list.get(i);
                if (setting.o_gameName != null) {
                    Attribute attribute = element.attribute("label");
                    if (attribute != null) {
                        attribute.setValue(setting.o_gameName);
                    }
                }
                if (false) {
                    List<Attribute> attList = element.attributes();
                    C_Log.LogFormat("Manifest元素.__________%d___________%s", i, element.getName());
                    for (int r = 0; r < attList.size(); r++) {
                        Attribute att = attList.get(r);
                        C_Log.LogFormat("application元素.属性原始值____________________%d___________%s_____%s", r, att.getName(), att.getValue());
                        String value = att.getValue();
                        if (value.startsWith(setting.o_lastPackageName)) {
                            String value1 = setting.o_packageName + value.subSequence(length0, value.length());
                            att.setValue(value1);
                            C_Log.LogFormat("application元素.属性修改后的值._______________________%d___________%s_____%s", r, att.getName(), att.getValue());
                        }
                    }
                }
            }
        }

        //fileName = fileName + ".xml";
        XmlUtil.saveElement(document, fileName);
        C_Log.Log("--------------build.S_fix_androidManifest..结束.________");
    }

    //---拷贝微信回调的类--------------
    static void S_copyWeiXinClass(String _build, String rootPath, String wordPath, build_config setting) {

        if (setting.o_packageName.length() <= 2) {
            return;
        }
        if (setting.o_packageName.equals(setting.o_lastPackageName)) {
            return;
        }
        C_Log.LogWarningFormat(".拷贝微信回调的类-....");
        String srcStr0 = setting.o_lastPackageName.replaceAll("/.", "/") + "/wxapi";
        String replaceStr0 = setting.o_packageName.replaceAll("/.", "/") + "/wxapi";

        String sourecDir = rootPath + _build + "/appUnfold/smali/" + srcStr0;
        String targetDir = rootPath + _build + "/appUnfold/smali/" + replaceStr0;

        C_File.S_moveDir_ReplacTextContent(sourecDir, targetDir, srcStr0, replaceStr0);
        C_Log.LogWarningFormat(".拷贝微信回调的类-...." + sourecDir);
    }

    //---拷贝微信回调的类--------------
    static void S_copyAssets(String _build, String rootPath, String wordPath) {
        String sourecDir = wordPath + "assets/";
        String targetDir = rootPath + _build + "/appUnfold/assets/";
        C_Log.LogWarningFormat(".开始.拷贝Assets...." + sourecDir);
        File sourec = new File(sourecDir);
        if (!sourec.exists()) {
            sourec.mkdirs(); //创建目录
            C_Log.LogError("目录==null...无法拷贝...." + sourecDir);
        } else {
            C_File.S_copyDir(sourecDir, targetDir);
        }
        C_Log.LogWarningFormat(".拷贝Assets.结束..." + sourecDir);
    }

    static void S_copyIcon(String _build, String rootPath, String wordPath) {
        C_Log.Log("build.S_copyIcon..开始.拷贝图标________");
        String sourcePath = wordPath + "icon.png";
        File file = new File(sourcePath);
        if (!file.exists()) {
            C_Log.LogErrorFormat("源icon不存在....无法替换........." + sourcePath);
            return;
        }
        for (String iconPath : iconPaths) {
            String targetPath = rootPath + _build + "/" + iconPath;
            File file2 = new File(targetPath);
            if (!file2.exists()) {
                C_Log.LogErrorFormat("目标icon不存在....无法替换........." + targetPath);
                continue;
            }
            C_File.S_fileCopy(sourcePath, targetPath);
        }
        C_Log.Log("build.S_copyIcon..拷贝图标_结束.________");
    }

    static String[] iconPaths = new String[]{
            "appUnfold/res/drawable/ic_launcher_foreground.png",
            "appUnfold/res/drawable-hdpi/app_icon.png",
            "appUnfold/res/drawable-ldpi/app_icon.png",
            "appUnfold/res/drawable-mdpi/app_icon.png",
            "appUnfold/res/drawable-xhdpi/app_icon.png",
            "appUnfold/res/drawable-xxhdpi/app_icon.png",
            "appUnfold/res/drawable-xxxhdpi/app_icon.png",

            "appUnfold/res/mipmap-hdpi/app_icon.png",
            "appUnfold/res/mipmap-hdpi/app_icon_round.png",
            "appUnfold/res/mipmap-ldpi/app_icon.png",
            "appUnfold/res/mipmap-ldpi/app_icon_round.png",
            "appUnfold/res/mipmap-mdpi/app_icon.png",
            "appUnfold/res/mipmap-mdpi/app_icon_round.png",
            "appUnfold/res/mipmap-xhdpi/app_icon.png",
            "appUnfold/res/mipmap-xhdpi/app_icon_round.png",
            "appUnfold/res/mipmap-xxhdpi/app_icon.png",
            "appUnfold/res/mipmap-xxhdpi/app_icon_round.png",
            "appUnfold/res/mipmap-xxxhdpi/app_icon.png",
            "appUnfold/res/mipmap-xxxhdpi/app_icon_round.png",
    };

    static void S_FixConfig(String _build, String rootPath, String wordPath, build_config setting) throws IOException {
        String path = rootPath + _build + "/appUnfold/assets/config.txt";
        build_config.S_FixConfig(path, setting);
    }


    static void S_apk2build(String _build, String rootPath, build_config setting) throws Exception {
        C_ProgressReport.S_SendProgress(setting, C_ProgressReport.o_app2build);
        C_Log.Log("--------build.S_apk2build..开始.2次打包________");
        String[] args = new String[4];
        args[0] = "b";
        args[1] = rootPath + _build + "/appUnfold";
        args[2] = "-o";
        args[3] = rootPath + _build + "/app2Build.apk";
        C_cmd.S_delete(args[3]);
        Main.main(args);
        if (build_config.o_isDelectTempFile) {
            C_cmd.S_delete(args[1]);
        }
        C_Log.Log("--------------build.S_apk2build..2次打包结束.________");
    }

    //[-storepass <口令>] 用于密钥库完整性的口令[-keypass <口令>] 私有密钥的口令 (如果不同)
    //jarsigner -verbose -keystore keybaohuai -storepass 123456 -keypass 123456 -digestalg SHA1 -sigalg MD5withRSA -signedjar AndroidTestsigned.apk zhaocaixiong101.apk baohuai
    static void S_apk2Sign(String _build, int index, String rootPath, String wordPath, build_config setting, String dirName) throws Exception {
        C_ProgressReport.S_SendProgress(setting, C_ProgressReport.o_app2Sign);
        C_Log.Log("--------build.S_apk2Sign..开始.2次签名________" + rootPath);
        if (!new File(rootPath + "sign.keystore").exists()) {
            //JOptionPane.showMessageDialog(null, setting.o_gameName + "--sign.keystore", "无法打包签名", JOptionPane.PLAIN_MESSAGE);
            return;
        }
        if (build_config.o_isDelectTempFile) {
            // C_File.S_delete(rootPath + _build + "/app2Signed_" + setting.o_gameName + ".apk");
        }

        String signPath = build_config.S_SearchFilePath(rootPath ,"sign.keystore");
        S_CheckExists(signPath);
        String app2BuildPath = rootPath + _build + "/app2Build.apk ";
        S_CheckExists(app2BuildPath);
        //String app2Signed_11 = rootPath + _build + "/" + String.format("%04d",(index + 1)) + "_" + dirName + "_" + setting.o_gameName + ".apk ";
        String app2Signed_11 = rootPath + _build + "/" + dirName + ".apk ";
        try {
            String cmd = "jarsigner -verbose -keystore " + signPath +
                    " -storepass " + setting.o_keystorePass + " -keypass " + setting.o_keystorePass + " -digestalg SHA1 -sigalg MD5withRSA" +
                    " -signedjar " + app2Signed_11 + "  " + app2BuildPath + "   " + setting.o_keyaliasName;
            C_Log.Log("S_apk2Sign.________" + cmd);
            C_cmd.S_Runtime(cmd);
        } catch (Exception e) {
            C_Log.LogError("S_apkSign.错误...", e);
            e.printStackTrace();//方法的意思是：在命令行打印异常信息在程序中出错的位置及原因。
        }
        C_cmd.S_delete(wordPath + _build + "/app2Build.apk");
        C_Log.Log("--------------build.S_apk2Sign..2次签名结束.________");
        C_ProgressReport.S_upload(setting, app2Signed_11);
    }

    public static void S_CheckExists(String path) {
        path = path.replace("/", "/");
        File file = new File(path);
        if (!file.exists()) {
            C_Log.LogError("超级错误..文件不存在..." + path);
        }
    }
}
